package com.qf.service.impl;

import com.qf.dao.OrderDao;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.pojo.Order;
import com.qf.pojo.OrderItem;
import com.qf.service.OrderService;
import com.qf.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

public class OrderServiceImpl implements OrderService {
    @Override
    public void addOrder(Order order) {
        //同时执行两个sql语句,加入事务控制,添加order和orderItem
        //初始化连接对象,确保事务中的连接对象是同一个
        Connection connection = null;
        //获取连接对象
        connection = JdbcUtils.getConnection();
        //开启事务
        try {
            connection.setAutoCommit(false);    //禁用事务自动提交,改为手动提交
            //调用数据层,添加数据
              OrderDao orderDao = new OrderDaoImpl();
              orderDao.insertOrder(order);
              //加入一个异常来测试事务是否成功
//            System.out.println(10/0);
            //执行第二个sql语句
            //遍历orderItem
            for (OrderItem orderItem:order.getItems()){
                //调用数据访问层,添加orderitem
                orderDao.insertOrderItem(orderItem);
            }
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            //若失败.则回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }



    }
}
